package com.gaswell.schedule;


import com.gaswell.entity.Qba01;
import com.gaswell.service.*;

import com.gaswell.utils.DateUtils;
import com.gaswell.utils.RedisEnumeration;
import com.gaswell.vo.Qba01Count;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.sql.Date;
import java.util.List;
import java.util.Set;


@Component
@EnableAsync
public class CleanTask {
    @Autowired
    QjService qjService;

    @Autowired
    JhRtuConfigService jhRtuConfigService;


    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    RDataService rDataService;

    @Autowired
    ZtAlarmService ztAlarmService;
    private static Integer dataNum = 0;

    private static boolean firststart = true;

    /**
     * 用于清理日数据每月统计的过期数据
     * 异步处理数据
     */
    @Async("threadPoolTaskExecutor_forclearQba01Count")
    @Scheduled(cron = "1 0 0 * * ?")
    public void clearQba01CountData() {
        Date ddl = new Date(System.currentTimeMillis()-DateUtils.DAY*30);

        Set<String> keys = redisTemplate.keys(RedisEnumeration.QBA01COUNT + "*");
//      循环所有的key，然后删除一月以后的数据
        for (String key : keys) {
            List<Qba01Count> range = redisTemplate.opsForList().range(key, 0, -1);
            for (int i = 0; i < range.size(); i++) {
                Qba01Count qba01Count = range.get(i);
                List<String> dates = qba01Count.getDates();
                List<String> conditions = qba01Count.getConditions();
                //              compare 当前时间小于指定时间 返回-1 等于返回0  大于返回1
                while (DateUtils.stringTosqldate(
                        dates.get(0)
                ).compareTo(ddl) == -1) {
                    dates.remove(i);
                    conditions.remove(i);
                }
//              如果没有数据了，直接删除就可以了

                if (dates.size() > 0) {
                    qba01Count.setDates(dates);
                    qba01Count.setConditions(conditions);
                    range.set(i, qba01Count);
                } else {
                    range.remove(i);
                }

            }
//          先删掉,再添加。用于更新redis
            redisTemplate.delete(key);
            redisTemplate.opsForList().rightPushAll(key, range);
        }
    }


}
